import React from 'react'

export default class List extends React.Component {
  constructor() {
    super()
    this.state = {
      listData: []
    }
  }

  componentWillMount() {
    this.getListData()
  }

  render() {
    return <div>
      <h2>我是列表</h2>
      <input type="text" ref="username" />
      <input type="button" value="增加" onClick={() => this.listAdd()} />
      {this.state.listData.map(item => <div key={item.id}>
        {item.name}-----{this.timeFilter(item.ctime)}------<input type="button" value="删除" onClick={() => this.listDel(item.id)} />
      </div>)}
    </div>
  }

  getListData = async () => {
    let { data } = await this.http.get('http://www.liulongbin.top:3005/api/getprodlist')
    this.setState({
      listData: data.message
    })
  }

  listDel = async (id) => {
    let res = await this.http.get('http://www.liulongbin.top:3005/api/delproduct/' + id)
    if (res.data.status === 0) {
      this.getListData()
    }
  }

  listAdd = async () => {
    let res = await this.http.post('http://www.liulongbin.top:3005/api/addproduct', { name: this.refs.username.value })
    if(res.data.status === 0) {
      this.getListData()
      this.refs.username.value = ''
    }
  }

  timeFilter = (data) => {
    let date = new Date(data)
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    let d = date.getDate()

    return `${y}-${m}-${d} qqqqqqqqq`
  }
}